package com.yunhe.option.listener;

import com.alibaba.excel.context.AnalysisContext;
import com.alibaba.excel.event.AnalysisEventListener;
import com.yunhe.common.exception.ArgumentErrorException;
import com.yunhe.common.exception.ObjectNotFoundException;
import com.yunhe.common.exception.UniqueConstraintsException;
import com.yunhe.option.domain.base.ImportEnumItems;
import com.yunhe.option.service.base.EnumService;

import java.util.ArrayList;
import java.util.Collection;
import java.util.List;

/**
 * @ClassName EnumItemsListener
 * @Description TODO
 * @Author HeTao
 * @Date 2021/3/3 12:11
 * @Version 1.0
 **/
public class EnumItemsListener extends AnalysisEventListener<ImportEnumItems> {

    /**
     * 每次读取excel的条数
     */
    private static final int BATCH_COUNT = 5120;

    private EnumService enumService;

    private List<String> errMessage;

    List<ImportEnumItems> importEnumItems = new ArrayList<>();
    public EnumItemsListener(EnumService itemService) {
        this.enumService = itemService;
        errMessage = new ArrayList<>();
    }

    @Override
    public void invoke(ImportEnumItems data, AnalysisContext context) {
        importEnumItems.add(data);
        // 达到BATCH_COUNT了，需要去存储一次数据库，防止数据几万条数据在内存，容易OOM
        if (importEnumItems.size() >= BATCH_COUNT) {
            try {
                errMessage.addAll(saveData());
            } catch (ArgumentErrorException e) {
                e.printStackTrace();
            } catch (UniqueConstraintsException e) {
                e.printStackTrace();
            } catch (ObjectNotFoundException e) {
                e.printStackTrace();
            }
            //  存储完成清理 list
            importEnumItems.clear();
        }
    }

    private Collection<? extends String> saveData() throws ArgumentErrorException, UniqueConstraintsException, ObjectNotFoundException {


        return enumService.importEnumAndItems(importEnumItems);
    }

    @Override
    public void doAfterAllAnalysed(AnalysisContext context) {
        try {
            errMessage.addAll(saveData());
        } catch (ArgumentErrorException e) {
            e.printStackTrace();
        } catch (UniqueConstraintsException e) {
            e.printStackTrace();
        } catch (ObjectNotFoundException e) {
            e.printStackTrace();
        }
        importEnumItems.clear();
    }


    public EnumService getEnumService() {
        return enumService;
    }

    public void setEnumService(EnumService enumService) {
        this.enumService = enumService;
    }

    public List<String> getErrMessage() {
        return errMessage;
    }

    public void setErrMessage(List<String> errMessage) {
        this.errMessage = errMessage;
    }
}
